package quexi.components
{	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	[Event(name="select", type="flash.events.Event")]
	public class List extends Sprite
	{
		private var _itemWidth:Number = 100;
		private var _itemHeight:Number = 20;
		private var _itemContainer:Sprite;
		private var _selectedIndex:int = -1;
		
		public function List()
		{
			_itemContainer 	= new Sprite();
			
			addChild(_itemContainer);
		}
		
		public function addItem(data:Object):void
		{
			var item:ListItem 	= new ListItem(_itemWidth, _itemHeight);
			item.data 	= data;
			item.y 		= _itemContainer.numChildren * _itemHeight;
			item.addEventListener(MouseEvent.CLICK, onSelect);
			_itemContainer.addChild(item);
		}
		
		public function set selectedIndex(value:int):void
		{
			if(_selectedIndex != value)
			{//判断是否值有变化
				if(_selectedIndex >= 0 && _selectedIndex < _itemContainer.numChildren)
				{
					ListItem(_itemContainer.getChildAt(_selectedIndex)).selected = false;
				}
				
				if(value >=0 && value < _itemContainer.numChildren)
				{
					_selectedIndex = value;
					ListItem(_itemContainer.getChildAt(_selectedIndex)).selected = true;
				}
			}
		}
		
		/**
		 * 选中栏的id
		 * @return  
		 */		
		public function get selectedIndex():int
		{
			return _selectedIndex;
		}
		
		/**
		 * 被选中的item
		 * @return  
		 */		
		public function get selectedItem():Object
		{
			if(_selectedIndex >= 0 && _selectedIndex < _itemContainer.numChildren)
			{
				return ListItem(_itemContainer.getChildAt(_selectedIndex)).data;
			}
			return null;
		}
		
		/**
		 * 清除list所有内容 
		 */		
		public function clearAll():void
		{
			_selectedIndex = -1;
			while(_itemContainer.numChildren > 0)
				removeChildAt(0);
		}
		
		/** 鼠标点击一个栏 */		
		private function onSelect(e:MouseEvent):void
		{
			var item:ListItem = e.target as ListItem;
			
			if(item != null)
			{
				var targetIndex:int = _itemContainer.getChildIndex(item);
				selectedIndex = targetIndex;
				dispatchEvent(new Event(Event.SELECT));
			}
		}
		
		//
	}
}